package com.cutefool.zero.code.admin.meta.column.support;

import com.cutefool.dsl.mybatis.core.dsl.builder.QueryDsl;
import com.cutefool.dsl.mybatis.core.dsl.operation.CuteCurdOperation;
import com.cutefool.rds.meta.libs.RdsFields;
import com.cutefool.rds.template.RdsTemplate;
import com.cutefool.zero.code.admin.dbms.service.DbmsService;
import com.cutefool.zero.code.admin.dbms.support.DbmsExecutor;
import com.cutefool.zero.code.admin.meta.model.context.RdsTemplateContext;
import com.cutefool.zero.code.core.domain.Db;
import com.cutefool.zero.code.core.domain.ModelColumn;
import jakarta.annotation.Resource;
import org.mybatis.dynamic.sql.SqlBuilder;
import org.springframework.stereotype.Component;

@Component
public class ColumnDbSupport {

    @Resource
    private DbmsService dbmsService;

    @Resource
    private DbmsExecutor dbmsExecutor;

    @Resource
    private RdsTemplateContext rdsTemplateContext;

    @Resource
    private CuteCurdOperation<ModelColumn> cuteCurdOperation;

    public RdsFields doColumnLibs(ModelColumn column) {
        // 查询对应的环境的配置
        Db devDb = dbmsService.getDevDb(column.getDbmsId());
        return ColumnDbSupport.doColumnLibs(column, devDb);
    }

    public static RdsFields doColumnLibs(ModelColumn column, Db devDb) {
        RdsFields libs = new RdsFields();
        libs.setDbName(devDb.getName());
        libs.setName(column.getName());
        libs.setTableName(column.getTableName());
        libs.setRemark(column.getRemark());
        libs.setNullable(column.getNullable());
        libs.setLen(column.getLen());
        libs.setType(column.getType());
        return libs;
    }

    public void doSyncToDb(Long id) {
        ModelColumn instance = ModelColumn.instance();
        QueryDsl<ModelColumn> queryDsl = QueryDsl.newInstance(instance, (where) -> where.and(instance.id(), SqlBuilder.isEqualTo(id)));
        this.cuteCurdOperation.get(queryDsl).ifPresent(this::doSyncToDb);
    }

    public void doSyncToDb(ModelColumn e) {
        // 查询对应的环境的配置
        Db devDb = dbmsService.getDevDb(e.getDbmsId());
        dbmsExecutor.doInitFunction(devDb);
        RdsTemplate rdsTemplate = rdsTemplateContext.get(devDb);
        RdsFields rdsFields = ColumnDbSupport.doColumnLibs(e, devDb);
        rdsTemplate.create(rdsFields);
    }
}
